<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 搜索框部分 -->
      <el-row :gutter="20">
        <el-col :span="9">
          <el-input placeholder="请输入内容" v-model="queryList.query" clearable @clear="getAllUser">
            <el-button slot="append" icon="el-icon-search" @click="getAllUser"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户信息列表部分 -->
      <el-table :data="userList" border>
        <el-table-column type="index" label="序号" width="60px"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="权限">
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="stateChange(scope.row.id, scope.row.mg_state)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="175px">
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <!-- 编辑用户的按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUser(scope.row.id)"
            ></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="open(scope.row.id)"></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="修改角色"
              placement="top-start"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-star-off"
                size="mini"
                @click="editRoles(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页部分 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryList.pagenum"
        :page-sizes="[2, 4, 8, 10]"
        :page-size="queryList.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户模态框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-form :model="addUserRuleForm" :rules="addRules" ref="ruleForm" label-width="100px">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="addUserRuleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input v-model="addUserRuleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="用户邮箱" prop="email">
          <el-input v-model="addUserRuleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="用户手机" prop="mobile">
          <el-input v-model="addUserRuleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetMsg">取 消</el-button>
        <el-button type="primary" @click="addUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户的模态框 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="eidtDialogVisible"
      width="50%"
      :before-close="eidtHandleClose"
    >
      <el-form :model="editUserRuleForm" :rules="editRules" ref="ruleForm" label-width="100px">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="editUserRuleForm.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="用户手机" prop="mobile">
          <el-input v-model="editUserRuleForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="用户邮箱" prop="email">
          <el-input v-model="editUserRuleForm.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserNo">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色的模态框 -->
    <el-dialog
      title="修改角色"
      :visible.sync="editRolesVisible"
      width="50%"
      :before-close="editRolesHandleClose"
    >
      <p>当前的用户：{{userInfo.username}}</p>
      <p>当前的角色：{{userInfo.role_name}}</p>
      <p>
        分配新角色：
        <el-select v-model="roleName" slot="prepend" placeholder="请选择">
          <el-option :label="item.roleName" :value="item.id" v-for="item in rolseArr" :key="item.id"></el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRolesOk">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAllApi,
  userStateApi,
  addUserApi,
  editUserApi,
  editUserInfoApi,
  deleteUserApi,
  getAllRolesApi,
  setRolesOkApi
} from "./api/index.js";
export default {
  data: function() {
    // 验证邮箱的合法性
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        return callback();
      }
      callback("请输入合法的邮箱");
    };
    // 验证手机号的合法性
    var checkMblie = (rule, value, callback) => {
      const regMoblie = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMoblie.test(value)) {
        return callback();
      }
      callback("请输入合法的手机号");
    };
    return {
      // 获取所有用户列的参数
      queryList: {
        query: "",
        pagenum: 1,
        pagesize: 2
      },
      // 修改用户权限传的参数uId
      uId: 0,
      // 修改用户权限传的参数type
      type: null,
      userList: [],
      total: 0,
      // 控制添加用户的模态框的显示与隐藏
      addDialogVisible: false,
      // 控制编辑用户的模态框的显示与隐藏
      eidtDialogVisible: false,
      // 控制角色分配的模态框的显示与隐藏
      editRolesVisible: false,
      // 添加用户的表单数据
      addUserRuleForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      // 编辑用户的表单数据
      editUserRuleForm: {
        // 因为编辑用户提交需要参数id
        id: "",
        username: "",
        email: "",
        mobile: ""
      },
      // 验证添加表单的合法性
      addRules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
          { min: 3, max: 15, message: "长度在 3 到 15 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入用户邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入用户手机  ", trigger: "blur" },
          { validator: checkMblie, trigger: "blur" }
        ]
      },
      // 验证编辑表单的合法性
      editRules: {
        email: [
          { required: true, message: "请输入用户邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入用户手机  ", trigger: "blur" },
          { validator: checkMblie, trigger: "blur" }
        ]
      },
      // 修改角色填充用户和角色的数据对象
      userInfo: {},
      // 分配新角色内获取的所有角色数据
      rolseArr: [],
      // 下拉框双向绑定显示的数据 这个数据是相对应的id
      roleName: '',
      // 用户id
      userId: '',
      // 角色ID
      rolesId: ''
    };
  },
  created() {
    this.getAllUser();
    this.getAllRoles()
  },
  methods: {
    // 获取所有的用户信息
    async getAllUser() {
      const { data: res } = await getAllApi(this.queryList);
      if (res.meta.status !== 200) return this.$message.error("获取数据失败");
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    // 监听每页显示的条数
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.queryList.pagesize = val;
      this.getAllUser();
    },
    // 监听当前显示的页数
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.queryList.pagenum = val;
      this.getAllUser();
    },
    // 修改用户权限
    async stateChange(uId, type) {
      this.uId = uId;
      this.type = type;
      const { data: res } = await userStateApi(this.uId, this.type);
      if (res.meta.status !== 200) {
        this.type = !this.type;
        return this.$message.error("设置状态失败");
      } else {
        this.$message.success("设置状态成功");
      }
    },
    // 点击取消清空添加用户逇输入框
    resetMsg() {
      // console.log(this);
      this.$refs.ruleForm.resetFields();
      this.addDialogVisible = false;
    },
    // 点击x关闭窗口 同时清空添加用户的输入框
    handleClose() {
      this.resetMsg();
    },
    // 点击添加用户的确认按钮预校验文本输入
    addUserInfo() {
      this.addDialogVisible = false;
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) return this.$message.error("添加用户失败");
        var { data: res } = await addUserApi(this.addUserRuleForm);
        if (res.meta.status !== 201) return;
        this.$message.success("添加用户成功");
        this.resetMsg();
        this.getAllUser();
      });
    },
    // 编辑用户将信息渲染到输入框
    async editUser(id) {
      // 将id保存起来，便于在编辑用户提交中得到id
      this.editUserRuleForm.id = id;
      this.eidtDialogVisible = true;
      const { data: res } = await editUserApi(id);
      if (res.meta.status !== 200) return this.$message.error("获取信息失败");
      // 将获取的信息填充到表单中
      this.editUserRuleForm.username = res.data.username;
      this.editUserRuleForm.mobile = res.data.mobile;
      this.editUserRuleForm.email = res.data.email;
    },
    // 点击编辑取消按钮 重置输入框
    editUserNo() {
      this.resetMsg();
      this.eidtDialogVisible = false;
    },
    // 点击编辑的x按钮 重置输入框
    eidtHandleClose() {
      this.editUserNo();
    },
    // 点击编辑用户的确定按钮发送请求
    async editUserInfo() {
      const { data: res } = await editUserInfoApi(this.editUserRuleForm);
      if (res.meta.status !== 200) return this.$message.error("更新用户失败");
      this.eidtDialogVisible = false;
      this.$message.success("更新用户成功");
      this.getAllUser();
    },
    // 点击删除的模态框
    open(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await deleteUserApi(id);
          this.getAllUser();
          this.eidtDialogVisible = false;
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 修改角色的监听函数
    editRoles(row) {
      this.userId = row.id
      this.editRolesVisible = true;
      this.userInfo = row;
    },
    // 获取所有角色列表
    async getAllRoles() {
      const {data: res} = await getAllRolesApi()
      if(res.meta.status !== 200) return this.$message.error('获取所有角色列表失败')
      this.rolseArr = res.data
    },
    // 点击修改角色的x关闭弹窗
    editRolesHandleClose() {
      this.editRolesVisible = false
    },
    // 确认提交修改角色
    async editRolesOk() {
      const {data: res} = await setRolesOkApi(this.userId, this.roleName)
      if(res.meta.status !== 200) return this.$message.error('设置角色失败')
      this.$message.success('设置角色成功')
      this.getAllUser();
      this.editRolesHandleClose()
      // 设置成功后清空下拉框内的内容
      this.roleName = ''
    }
  }
};
</script>

<style lang="less" scoped>
.addForm > .el-input {
  margin-top: 10px;
}
.el-table {
  width: 99.9% !important;
}
</style>
